/**
 * Iterator
 * TypedArray
 * ModeList
 * arguments
 * 
 * 接口机制，为不同数据结构提供统一访问机制
 * for ... of
 * 实现 不支持遍历的数据结构可遍历
 * 
 * 可迭代协议： 是否有 Symbol.iterator 属性 for of
 * 迭代器协议：return {next(){return{value, done}}}
 */
function makeIterator(arr) {
  let nextIndex = 0
  return {
    next() {
      return nextIndex < arr.length ?{
        value: arr[nextIndex++],
        done: false
      } : {
        value: undefined,
        done: true
      }
    }
  }
}

let it = makeIterator(['a','b','c'])
console.log(it.next())
console.log(it.next())
console.log(it.next())

let course = {
  allCourse: {
    frontend: ['es','applet','vue','react'],
    backend: ['java','python'],
    webapp: ['android', 'ios']
  }
}

course[Symbol.iterator] = function () {
  let allCourse = this.allCourse
  let keys = Reflect.ownKeys(allCourse)
  let values = []
  return {
    next(){
      if(!values.length){
        if(keys.length){
          values = allCourse[keys[0]]
          keys.shift()
        }
      }
      return{
        done: !values.length,
        value: values.shift()  // 删除第一个 并返回删除结果
      }
    }
  }
}




// generator
course[Symbol.iterator] = function* () {
  let allCourse = this.allCourse
  let keys = Reflect.ownKeys(allCourse)
  let values = []
  while(1) {
    if(!values.length){
      if(keys.length){
        values =allCourse[keys[0]]
        keys.shift()
        yield values.shift()
      } else {
        return false
      }
    } else {
      yield values.shift()
    }
  }
}

// Invalid attempt to iterate non-iterable instance
for(let c of course){
  console.log(c)
}

/* let arr = ['a','b','c']
console.log(arr)
let it2 = arr[Symbol.iterator]()
console.log(it2.next())
console.log(it2.next())
console.log(it2.next())

let map = new Map()
map.set('name', 'es')
console.log(map)
let it3 = map[Symbol.iterator]()
console.log(it3.next()) */